package com.rlz.framemm.util

import com.rlz.base.util.single.Single
import com.tencent.mmkv.MMKV

/**
 * Created by RLZ
 * on 2021/11/5
 *
 */
class States {

    companion object : Single<States>(::States)

    private var mKV: MMKV? = MMKV.defaultMMKV()

    fun <T> save(key: String?, t: T) {
        when (t) {
            is String -> {
                mKV!!.encode(key, t as String)
            }
            is Int -> {
                mKV!!.encode(key, (t as Int))
            }
            is Boolean -> {
                mKV!!.encode(key, (t as Boolean))
            }
            is Long -> {
                mKV!!.encode(key, (t as Long))
            }
            is Double -> {
                mKV!!.encode(key, (t as Double))
            }
            is Float -> {
                mKV!!.encode(key, (t as Float))
            }
        }
    }

    fun getString(key: String?): String? {
        return if (mKV!!.decodeString(key) == null) "" else mKV!!.decodeString(key)
    }

    fun getInt(key: String?): Int {
        return mKV!!.decodeInt(key)
    }

    fun getLong(key: String?): Long {
        return mKV!!.decodeLong(key)
    }

    fun getFloat(key: String?): Float {
        return mKV!!.decodeFloat(key)
    }

    fun getDouble(key: String?): Double {
        return mKV!!.decodeDouble(key)
    }

    fun getBoolean(key: String?): Boolean {
        return mKV!!.decodeBool(key)
    }

    fun clear() {
        mKV!!.clear().apply()
    }
}